from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from server.db.base import BaseModel

# 关联表：用户-角色多对多关系
user_roles = Table(
    'user_roles',
    BaseModel.metadata,
    Column('user_id', Integer, ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
    Column('role_id', Integer, ForeignKey('roles.id', ondelete='CASCADE'), primary_key=True),
    Column('created_at', DateTime, default=datetime.utcnow)
)

# 关联表：角色-权限多对多关系
role_permissions = Table(
    'role_permissions',
    BaseModel.metadata,
    Column('role_id', Integer, ForeignKey('roles.id', ondelete='CASCADE'), primary_key=True),
    Column('permission_id', Integer, ForeignKey('permissions.id', ondelete='CASCADE'), primary_key=True),
    Column('created_at', DateTime, default=datetime.utcnow)
)

class User(BaseModel):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, nullable=False, index=True)
    email = Column(String(100), unique=True, nullable=False, index=True)
    phone = Column(String(20), unique=True, nullable=True)
    hashed_password = Column(String(100), nullable=False)
    salt = Column(String(32), nullable=False)
    status = Column(Integer, default=1, comment='状态(0-禁用,1-正常)')
    last_login_at = Column(DateTime)
    avatar = Column(String(255), nullable=True)
    remark = Column(Text, nullable=True)

    # 关系
    roles = relationship('Role', secondary=user_roles, back_populates='users')

    def has_permission(self, permission_code: str) -> bool:
        """检查用户是否拥有指定权限"""
        for role in self.roles:
            if any(perm.code == permission_code for perm in role.permissions):
                return True
        return False

class Role(BaseModel):
    __tablename__ = 'roles'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, nullable=False)
    description = Column(Text, nullable=True)
    status = Column(Integer, default=1, comment='状态(0-禁用,1-启用)')

    # 关系
    users = relationship('User', secondary=user_roles, back_populates='roles')
    permissions = relationship('Permission', secondary=role_permissions, back_populates='roles')

class Permission(BaseModel):
    __tablename__ = 'permissions'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, nullable=False)
    code = Column(String(100), unique=True, nullable=False)
    module = Column(String(50), nullable=False, comment='所属模块')
    description = Column(Text, nullable=True)

    # 关系
    roles = relationship('Role', secondary=role_permissions, back_populates='permissions')